package com.qcu.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qcu.annotation.LimitRate;
import com.qcu.annotation.RequireAuthorization;
import com.qcu.entity.Inhabitant;
import com.qcu.entity.User;
import com.qcu.exception.RepeatException;
import com.qcu.service.InhabitantService;
import com.qcu.util.Response;
import com.qcu.util.ResponseCode;
import com.qcu.util.ThreadLocalUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.swing.*;
import java.util.Map;
import java.util.Objects;

/**
 * @Name: MyComputer
 * @ClassName InhabitantController
 * @Description:
 * TODO: 进行操作前需要验证居民是否被当前用户所包含
 * @date 2025/2/6 13:14
 */

@RestController
@RequestMapping("/user/inhabitant")
public class InhabitantController {
    @Resource
    private InhabitantService inhabitantService;

    /**
     * 绑定居民信息到当前用户
     * @param inhabitant
     * @return
     */
    @PostMapping("/save")
    @RequireAuthorization({"USER"})
    public Response save(@RequestBody Inhabitant inhabitant)throws RepeatException {
        try {
            Map<String,Object> map = ThreadLocalUtil.get();
            Integer id = (Integer) map.get("id");
            inhabitant.setUserId(id);
            boolean save = inhabitantService.save(inhabitant);
            return save ? Response.success() : Response.failure(ResponseCode.FAILURE, "添加失败");
        } catch (Exception e) {
            throw new RepeatException(e.getMessage());
        }
    }

    /**
     * 修改居民信息
     * @param inhabitant
     * @return
     */
    @PutMapping("/update")
    @RequireAuthorization({"USER"})
    public Response update(@RequestBody Inhabitant inhabitant){
        //todo: 判断是否属于当前用户
        return inhabitantService.updateById(inhabitant) ? Response.success() : Response.failure(ResponseCode.FAILURE, "修改信息失败");
    }

    /**
     * 删除居民信息
     * @param id
     * @return
     */
    @DeleteMapping("/remove/{id}")
    @RequireAuthorization({"USER"})
    public Response remove(@PathVariable String id){
        //todo:判断是否属于当前用户

        return inhabitantService.removeById(id) ? Response.success() : Response.failure(ResponseCode.FAILURE, "删除失败");
    }

    /**
     * 获取居民信息
     * @return
     */
    @GetMapping("/get")
    @LimitRate(key = "getInhabitant",permitsPerSecond = 2,expire = 10,msg = "八嘎雅鹿，你滴点那么快滴干什么滴干活...")
    @RequireAuthorization({"USER"})
    public Response get(){
        Map<String,Object> map = ThreadLocalUtil.get();
        System.out.println(map);
        Integer o = (Integer) map.get("id");
        LambdaQueryWrapper<Inhabitant> inhabitantLambdaQueryWrapper = new LambdaQueryWrapper<>();
        inhabitantLambdaQueryWrapper.eq(Inhabitant::getUserId, o);
        return Response.success(inhabitantService.list(inhabitantLambdaQueryWrapper));
    }

}
